/*
 * @Author: Nice-2-CU 81088875+Nice-2-CU@users.noreply.github.com
 * @Date: 2023-07-11 21:32:36
 * @LastEditors: Nice-2-CU 81088875+Nice-2-CU@users.noreply.github.com
 * @LastEditTime: 2023-07-19 15:59:26
 * @FilePath: \lost-found-web\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import Cookies from "js-cookie";
import { Message } from 'element-ui';

// create an axios instance
const service = axios.create({
  baseURL: '/api'
})

service.interceptors.request.use(config => {
  const user_token = Cookies.get("user_token")
  if(user_token) {
    config.headers.satoken = JSON.parse(user_token).tokenValue
  } else {
    config.headers.satoken = null
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(function (response) {
  if(response.data.code === 200) {
    return response
  } else if(response.data.code === 401) {
    Cookies.remove("user")
    Cookies.remove("user_token")
    location.reload()
    Message.error({
      message: response.data.msg,
      duration: 1000
    })
  } else if(response.data.code === 403) {
    Message.error({
      message: response.data.msg,
      duration: 1000
    })
  } else {
    Message.error({
      message: response.data.message,
      duration: 1000
    })
  }
  return response
}, function (error) {
  return Promise.reject(error);
})

export default service
